package com.pub.web;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.Cookie;
import com.pub.tools.PublicFunction;
import com.pub.database.DBFunction;
import com.pub.database.QueryBean;
import java.util.*;
import com.pub.Constans;

public class WebFunction {
    private static boolean blnDebug = false;
    public WebFunction() {
    }

    /**
     *
     * @param strString String
     * @param strTagS String
     * @param strTagE String
     * @return String
     */
    public static String splitString(String strString, String strTagS,
                                     String strTagE) {
        final String strMethodName = "splitString"; //method name
        String ls_rtn = ""; //用來回傳值用的
        try {
            if ((!strString.equals("")) && (!strTagS.equals("")) &&
                (!strTagE.equals(""))) {
                ls_rtn = strString.substring(strString.indexOf(strTagS) +
                                             strTagS.length(),
                                             strString.indexOf(strTagE));
            }
        } catch (Exception e) {
            System.out.println("\nPublicCheck.java (" + strMethodName +
                               ") --> Exception : " + e.toString());
            System.out.println("PublicCheck.java (" + strMethodName +
                               ") --> 傳入錯誤的字串 : " + strString);
            System.out.println("PublicCheck.java (" + strMethodName +
                               ") --> 傳入strTagS : " + strTagS + "  strTagE=" +
                               strTagE + "\n");
        }
        return ls_rtn; //回傳結果
    } //End - splitString

    /*目的：從Portal的cookie中取出empno，並設定到session中
      傳入：httpServletRequest
      傳回：true成功,false失敗
      範例：boolean blnFlag = new PublicCheck().setPortal_to_session(httpServletRequest); */
    public boolean setPortal_to_session(HttpServletRequest httpServletRequest) {
        boolean blnFlag = true;
        String userId = "", strUsername = "";
        try {
            //步驟1：從cookie中得到userId
            Cookie[] cookies = httpServletRequest.getCookies();
            if (blnDebug) {
                System.out.println(
                        "PublicCheck.java (setPortal_to_session) --> ");
            }
            if (blnDebug) {
                System.out.println("cookies -> " + cookies);
            }
            if (cookies == null) {
                return blnFlag = false; //無cookies時
            }
            String ckName = null;
            String ckValue = null;
            if (blnDebug) {
                System.out.println("cookies.length=" + cookies.length);
            }
            for (int i = 0; i < cookies.length; i++) {
                ckName = cookies[i].getName();
                ckValue = cookies[i].getValue();
                if (blnDebug) {
                    System.out.println(ckName + " : " + ckValue);
                }
                //hws0425 增加判斷u_id
                if (ckName != null &&
                    ("ldapid".equalsIgnoreCase(ckName) ||
                     "u_id".equalsIgnoreCase(ckName))) {
                    userId = cookies[i].getValue(); //取到portal上的empno的cookie
                    if (!userId.equalsIgnoreCase("")) { //hws0425
                        if ("u_id".equalsIgnoreCase(ckName)) {
                            cookies[i].setValue(null); //hws0425
                        }
                        break;
                    }
                }
            } //end-for
            //步驟2：將cookie設定到session中
            if (userId!=null && !userId.trim().equals("") && !userId.trim().equals("null")) {
                httpServletRequest.getSession().setAttribute("u_id", userId); //指定sessioin
                blnFlag = true;
                if (blnDebug) {
                    System.out.println("** userId=" + userId + " strUsername=" +
                                       strUsername);
                }
            }
        } catch (Exception ex) {
            System.out.println("\nPublicCheck.java" +
                               " method:setPortal_to_session --> Exception=" +
                               ex.toString());
        } finally {
            if (blnDebug) {
                if (blnFlag) {
                    System.out.println("** setPortal_to_session success!! **");
                } else {
                    System.out.println("** setPortal_to_session fail!! **");
                }
            }
        }
        return blnFlag;
    } //setPortal_to_session

    /**
     * 將URI中含有Http 傳送的保留字取代成特殊符號
     * @param pstrURI 要轉換的URI
     * @return String 轉換後的URI
     */
    public static String replaceReserveCharOnPageSubmit(String pstrURI) {
        String lstrURI = pstrURI;
        try {
            if (lstrURI.trim().length() > 0) {
                lstrURI = lstrURI.replaceAll("\"", "”");
                lstrURI = PublicFunction.replace(lstrURI, "'", "^*", false);
                lstrURI = PublicFunction.replace(lstrURI, "'", "`", false);
                lstrURI = PublicFunction.replace(lstrURI, "%", "％", false);
                lstrURI = PublicFunction.replace(lstrURI, "+", "＋", false);
                lstrURI = PublicFunction.replace(lstrURI, "=", "＝", false);
                lstrURI = PublicFunction.replace(lstrURI, "=", "ˊ", false); //2004-12-16 昕晏系統出錯改的
                lstrURI = PublicFunction.replace(lstrURI, "(+)", "(ㄚ)", false); //2004-12-16 昕晏系統出錯改的
                lstrURI = PublicFunction.replace(lstrURI, "=", "杓", false); //2004-12-16 昕晏系統出錯改的
            }
        } catch (Exception ex) {
            System.out.println("\nWebFunction.java" +
                               " method:replaceReserveCharOnPageSubmit --> Exception=" +
                               ex.toString());
        }
        return lstrURI;
    }

    public static String transferToHtmlTable(Hashtable<String,Hashtable<String,Object>> phtRowData,String pstrTableProperty) throws Exception{
        StringBuffer lstbHtml = new StringBuffer();
        ArrayList<String> larlKeys = null;

        try{
            if(phtRowData==null || phtRowData.size()==0){
                return null;
            }

            lstbHtml.append("<table ");

            if(pstrTableProperty!=null && !pstrTableProperty.trim().equals("")){
                lstbHtml.append(pstrTableProperty);
            }

            lstbHtml.append(">");

            larlKeys = Collections.list(((Hashtable<String,Object>)phtRowData.get("0")).keys());

            lstbHtml.append("<tr>");

            for(int i=0;i<larlKeys.size();i++){
                lstbHtml.append("<th>");
                lstbHtml.append(larlKeys.get(i).toString());
                lstbHtml.append("</th>");
                //System.out.println(i + "==>" + larlKeys.get(i).toString());
            }

            lstbHtml.append("</tr>");

            for(int i=0;i<phtRowData.size();i++){
                lstbHtml.append("<tr>");
                for(int j=0;j<larlKeys.size();j++){
                    lstbHtml.append("<td>");
                    lstbHtml.append(((Hashtable<String,Object>)phtRowData.get(String.valueOf(i))).get(larlKeys.get(j).toString()));
                    lstbHtml.append("</td>");
                }
                lstbHtml.append("</tr>");
            }



            lstbHtml.append("</table>");
        }
        catch(Exception e){
            throw new Exception(e.fillInStackTrace());
        }
        finally{

        }

        return lstbHtml.toString();
    }

    /**
     * 將透過ReplaceReverseCharOnPageSubmit 的URI反轉回來
     * @param pstrURI 要轉換的URI
     * @return String 轉換後的URI
     */
    public static String unReplaceReserveCharOnPageSubmit(String pstrURI) {
        String lstrURI = pstrURI;
        try {
            if (lstrURI.trim().length() > 0) {
                lstrURI = lstrURI.replaceAll("”", "\"");
                lstrURI = PublicFunction.replace(lstrURI, "^*", "'", false);
                lstrURI = PublicFunction.replace(lstrURI, "`", "'", false);
                lstrURI = PublicFunction.replace(lstrURI, "％", "%", false);
                lstrURI = PublicFunction.replace(lstrURI, "＋", "+", false);
                lstrURI = PublicFunction.replace(lstrURI, "＝", "=", false);
                lstrURI = PublicFunction.replace(lstrURI, "ˊ", "=", false); //2004-12-16 昕晏系統出錯改的
                lstrURI = PublicFunction.replace(lstrURI, "(ㄚ)", "(+)", false); //2004-12-16 昕晏系統出錯改的
                lstrURI = PublicFunction.replace(lstrURI, "杓", "=", false); //2004-12-16 昕晏系統出錯改的
            }
        } catch (Exception ex) {
            System.out.println("\nWebFunction.java" +
                               " method:unReplaceReserveCharOnPageSubmit --> Exception=" +
                               ex.toString());
        }
        return lstrURI;
    }

    public static String replaceReserveCharOnWebPage(String pstrText) {
        String lstrText = pstrText;
        try {
            if (lstrText.trim().length() > 0) {
                lstrText = PublicFunction.replace(lstrText, "\"", "&quot;", false);
                //lstrText=PublicFunction.replace(lstrText," ","&nbsp;",false);
            }
        } catch (Exception e) {
            System.out.println("\nWebFunction.java" +
                               " method:replaceReserveCharOnWebPage --> Exception=" +
                               e.toString());
        }
        return lstrText;
    }

    public static String unReplaceReserveCharOnWebPage(String pstrText) {
        String lstrText = pstrText;
        try {
            if (lstrText.trim().length() > 0) {
                lstrText = PublicFunction.replace(lstrText, "&quot;", "\"", false);
                //lstrText=PublicFunction.replace(lstrText,"&nbsp;"," ",false);
            }
        } catch (Exception e) {
            System.out.println("\nWebFunction.java" +
                               " method:unReplaceReserveCharOnWebPage --> Exception=" +
                               e.toString());
        }
        return lstrText;
    }

    /**
     * 將SQL值轉成HTML Option taglib
     * @param pstrDBAlias 要connect的db 別名
     * @param pblnDBDebug 執行sql command時是否要開啟debug mode
     * @param pstrSourceCharset 前端(page) encodeing
     * @param pstrTargetCharset 後端(db) 編碼
     * @param pstrSQL 傳入的SQL，只能select 兩個欄位，第一欄為option value，第二欄為display value
     * @param pstrSelectedValue 下拉式選單Default要選的值
     * @return String 內含<Option value='1'>1</option>的字串
     * @sample
     * <select name="cat_no" CLASS="select" id="cat_no">
          <option value=""></option>
          <%=WebFunction.transferRSToHtmlOption(view.getDBAlias(),view.getDBDebug(),view.getSourceCharset(),view.getTargetCharset(),"select cat_no,cat_name from pms_cat where cat_type='"+view.getcat_type()+"'",view.getcat_no())%>
       </select>
     */
    public static String transferRSToHtmlOption(String pstrDBAlias,
                                                boolean pblnDBDebug,
                                                String pstrSourceCharset,
                                                String pstrTargetCharset,
                                                String pstrSQL,
                                                String pstrSelectedValue) {
        QueryBean lqbnDAO = null;

        try {
            lqbnDAO = new QueryBean(pstrDBAlias, pblnDBDebug, pstrSourceCharset,
                                    pstrTargetCharset);
            return transferRSToHtmlOption(lqbnDAO,pstrSQL,pstrSelectedValue);

        } catch (Exception e) {
            System.out.println("\nWebFunction.java" +
                               " method:transferRSToHtmlOption --> Exception=" +
                               e.toString());
            return "";

        } finally {
            if (lqbnDAO != null) {
                try {
                    lqbnDAO.close();
                } catch (Exception se) {
                    System.out.println(
                            "\ncan't close querybean in WebFunction.java" +
                            " method:transferRSToHtmlOption --> Exception=" +
                            se.toString());
                }

                lqbnDAO = null;
            }
        }
    }
    /**
     * 將SQL值轉成HTML Option taglib
     * @param pqbnDAO QueryBean object instance.
     * @param pstrSQL 傳入的SQL，只能select 兩個欄位，第一欄為option value，第二欄為display value
     * @param pstrSelectedValue 下拉式選單Default要選的值
     * @return String 內含<Option value='1'>1</option>的字串
     * @sample
     * <select name="cat_no" CLASS="select" id="cat_no">
          <option value=""></option>
          <%=WebFunction.transferRSToHtmlOption(gqbnDAO,"select cat_no,cat_name from pms_cat where cat_type='"+view.getcat_type()+"'",view.getcat_no())%>
       </select>
     */
    public static String transferRSToHtmlOption(QueryBean pqbnDAO,
                                                String pstrSQL,
                                                String pstrSelectedValue) {
        StringBuffer lstbOptions = null;
        ArrayList<ArrayList<Object>> laryData = null;

        try {
            lstbOptions = new StringBuffer();
            laryData = pqbnDAO.querySQL(pstrSQL);

            if(laryData==null){return "";}

            for (int i = 0; i < laryData.size(); i++) {
                lstbOptions.append("<option value='");
                lstbOptions.append(((ArrayList<Object>) laryData.get(i)).get(0).
                                   toString());
                lstbOptions.append("'");
                if (((ArrayList<Object>) laryData.get(i)).get(0).toString().equals(
                        pstrSelectedValue)) {
                    lstbOptions.append(" selected ");
                }
                lstbOptions.append(">");
                lstbOptions.append(((ArrayList<Object>) laryData.get(i)).get(1).
                                   toString());
                lstbOptions.append("</option>");
            }
            return lstbOptions.toString();

        } catch (Exception e) {
            System.out.println("\nWebFunction.java" +
                               " method:transferRSToHtmlOption --> Exception=" +
                               e.toString());
            return "";

        } finally {
            if (laryData != null) {
                laryData.clear();
                laryData = null;
            }
        }
    }

    public static String transferRSToHtmlOptionForJS(QueryBean pqbnDAO,
                                                String pstrSQL,
                                                String pstrSelectedValue) {
        StringBuffer lstbOptions = null;
        ArrayList<ArrayList<Object>> laryData = null;

        try {
            lstbOptions = new StringBuffer();
            laryData = pqbnDAO.querySQL(pstrSQL);

            lstbOptions.append("//false,"); //第一個選項都是空白

            if(laryData==null){return "";}

            for (int i = 0; i < laryData.size(); i++) {
                lstbOptions.append(((ArrayList<Object>) laryData.get(i)).
                                   get(1).toString());
                lstbOptions.append("/");
                lstbOptions.append(((ArrayList<Object>) laryData.get(i)).
                                  get(0).toString());
                lstbOptions.append("/");
                lstbOptions.append((pstrSelectedValue.equals(((ArrayList<Object>) laryData.get(i)).
                                  get(0).toString()) ? "true" : "false"));

                if (i != laryData.size() - 1) {
                    lstbOptions.append(",");
                }
            }
            return lstbOptions.toString();

        } catch (Exception e) {
            System.out.println("\nWebFunction.java" +
                               " method:transferRSToHtmlOption --> Exception=" +
                               e.toString());
            return "";

        } finally {
            if (laryData != null) {
                laryData.clear();
                laryData = null;
            }
        }
    }

    public static String transferRSToHtmlOptionForJS(String pstrDBAlias,
                                                boolean pblnDBDebug,
                                                String pstrSourceCharset,
                                                String pstrTargetCharset,
                                                String pstrSQL,
                                                String pstrSelectedValue) {
        QueryBean lqbnDAO = null;

        try {
            lqbnDAO = new QueryBean(pstrDBAlias, pblnDBDebug, pstrSourceCharset,
                                    pstrTargetCharset);
            return transferRSToHtmlOptionForJS(lqbnDAO,pstrSQL,pstrSelectedValue);

        } catch (Exception e) {
            System.out.println("\nWebFunction.java" +
                               " method:transferRSToHtmlOption --> Exception=" +
                               e.toString());
            return "";

        } finally {
            if (lqbnDAO != null) {
                try {
                    lqbnDAO.close();
                } catch (Exception se) {
                    System.out.println(
                            "\ncan't close querybean in WebFunction.java" +
                            " method:transferRSToHtmlOption --> Exception=" +
                            se.toString());
                }

                lqbnDAO = null;
            }
        }
    }
    /**
     * getMenuData
     *
     * @param pstrFrameID String
     * @param pstrUserID String
     * @param pstrDBAlias String
     * @param pblnDebug boolean
     * @param pstrSourceCharset String
     * @param pstrTargetCharset String
     * @return String
     */
    public static String getMenuData(String pstrFrameID,String pstrUserID,String pstrDBAlias,boolean pblnDebug,String pstrSourceCharset,String pstrTargetCharset){
        QueryBean lqbnDAO=null;
        ArrayList<ArrayList<Object>> larylstData = null;
        StringBuffer lstbMenuData=new StringBuffer();
        StringBuffer lstbSQL = new StringBuffer();
        StringBuffer lstbSysGroupList = null;

        try{
            lqbnDAO = new QueryBean(pstrDBAlias,pblnDebug,pstrSourceCharset,pstrTargetCharset);

            lstbSQL.append("select sys_group from wkf_frame where frame_no='");
            lstbSQL.append(pstrFrameID);
            lstbSQL.append("'");

            lstbSysGroupList = new StringBuffer(PublicFunction.replace(lqbnDAO.readSingleValueData(lstbSQL.toString()),",","','",false));

            lstbSQL.delete(0,lstbSQL.length());

            lstbSysGroupList.insert(0,"('");
            lstbSysGroupList.append("')");
            
            lstbSQL.append("select type_id ").append(DBFunction.getConStrSybtax(lqbnDAO.getDBType())).append(" '=insFld(' ").append(DBFunction.getConStrSybtax(lqbnDAO.getDBType())).append(" type_up ").append(DBFunction.getConStrSybtax(lqbnDAO.getDBType())).append(" ',gFld(′' ").append(DBFunction.getConStrSybtax(lqbnDAO.getDBType())).append(" type_name ").append(DBFunction.getConStrSybtax(lqbnDAO.getDBType())).append(" '′,′' ").append(DBFunction.getConStrSybtax(lqbnDAO.getDBType())).append(" ").append(DBFunction.getNullToValueSyntax(lqbnDAO.getDBType(), "url", "''")).append(" ").append(DBFunction.getConStrSybtax(lqbnDAO.getDBType())).append(" '′))'");
            lstbSQL.append(" from wkf_menu where sys_no in ");
            lstbSQL.append(lstbSysGroupList.toString());
            lstbSQL.append(" AND type_status<>'N' AND ( type_status='C' OR type_status='O' OR ((type_status='P' OR type_status='D') AND type_up IN (SELECT type_id FROM wkf_menu WHERE sys_no IN ");
            lstbSQL.append(lstbSysGroupList.toString());
            lstbSQL.append(" AND (type_status='C' OR type_status='O')) ) ) AND ( type_status='C' OR type_status='O' OR  type_id IN (SELECT prg_no FROM wkf_prg_right WHERE ( group_no IN (SELECT group_no FROM wkf_group WHERE user_no='");
            lstbSQL.append(pstrUserID);
            lstbSQL.append("') AND p1='Y'))) ORDER BY flag,seqno");
            //lstbSQL.append("");
            //lstbSQL.append("");

            //System.out.println(lstbSQL.toString());

            larylstData = lqbnDAO.querySQL(lstbSQL.toString());

            for(int i=0;i<larylstData.size();i++){
                lstbMenuData.append(PublicFunction.replace(((ArrayList<Object>)larylstData.get(i)).get(0).toString(),"′","'",false));
                lstbMenuData.append("\n");
            }
        }
        catch(Exception e){

        }
        finally{
            if(lqbnDAO!=null){
                try {
                    lqbnDAO.close();

                } catch (Exception se) {
                    System.out.println(
                            "\ncan't close querybean in WebFunction.java" +
                            " method:getMenuData --> Exception=" +
                            se.toString());

                }
                lqbnDAO = null;
            }
            if(larylstData!=null){
                larylstData.clear();
                larylstData=null;
            }

        }
        return lstbMenuData.toString();
    }

    public static String getReloadPortalScript(String pstrPortal,String pstrDBAlias) throws Exception{
        String lstrResult=null;

        if(pstrPortal==null){
            lstrResult="opener.location.href='/PUBPAGE/WKF_JST_ENG.jsp?db_alias=" + pstrDBAlias + "';";
        }
        else if(pstrPortal.equals("Y")){
            lstrResult="opener.location.href='" + Constans.gstrPortalURI + "';";
        }
        else{
            lstrResult="location.href='" + Constans.gstrWkfURI + "';";
        }

        return lstrResult;
    }
}
